package top.makeprogress.taobaospider.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import java.util.List;

/**
 * @author liuyi
 * @create 2019-10-13 10:04
 **/

public class ExcelUtils {
    /**
     * @param sheetName
     * @param titleList
     * @param rowList
     * @param wb
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, List<String> titleList, List<List<String>> rowList, HSSFWorkbook wb) {
        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        if (wb == null) {
            wb = new HSSFWorkbook();
        }
        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
        //创建title
        createSheetRowCells(sheet, style, 0, titleList);
        //创建内容
        for (int i = 0; i < rowList.size(); i++) {
            createSheetRowCells(sheet, i + 1, rowList.get(i));
        }
        return wb;
    }

    /**
     * 创建row并将cell赋值
     *
     * @param sheet
     * @param rowNum
     * @param cellList
     */
    private static void createSheetRowCells(HSSFSheet sheet, Integer rowNum, List<String> cellList) {
        HSSFRow row = sheet.createRow(rowNum);
        for (int i = 0; i < cellList.size(); i++) {
            row.createCell(i).setCellValue(cellList.get(i));
        }
    }

    /**
     * 创建row并赋值cell,并设置cell的样式
     *
     * @param sheet
     * @param cellStyle
     * @param rowNum
     * @param cellList
     */
    private static void createSheetRowCells(HSSFSheet sheet, HSSFCellStyle cellStyle, Integer rowNum, List<String> cellList) {
        HSSFRow row = sheet.createRow(rowNum);
        HSSFCell cell;
        for (int i = 0; i < cellList.size(); i++) {
            cell = row.createCell(i);
            cell.setCellValue(cellList.get(i));
            cell.setCellStyle(cellStyle);
        }
    }


}
